﻿using Model.DocumentDB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace Studio.DocumentDB.Dialogs
{
    /// <summary>Window querying the user about a new document.</summary>
    public partial class NewDocumentWindow : Window
    {
        /// <summary>Collection.</summary>
        /// <remarks>Input by the consumer.</remarks>
        public CollectionViewModel Collection { get; set; }

        /// <summary>Constructor.</summary>
        public NewDocumentWindow()
        {
            InitializeComponent();

            ValidateForm();
        }

        /// <summary>Sets the data context for data binding.</summary>
        /// <param name="e"></param>
        protected override void OnActivated(EventArgs e)
        {
            base.OnActivated(e);

            DataContext = Collection;
        }

        private async void Ok_Click(object sender, RoutedEventArgs e)
        {
            await ErrorHelper.HandleAsync(
                async () =>
                {
                    var content = docText.Text;
                    var task = Collection.CreateDocumentAsync(content);
                    var waitWindow = new WaitWindow
                    {
                        WaitingTask = task,
                        Owner = Window.GetWindow(this)
                    };

                    waitWindow.ShowDialog();

                    await task;
                    DialogResult = true;
                }, this, "New Document:  {0}");
        }

        private void ValidateForm()
        {
            okButton.IsEnabled = !string.IsNullOrWhiteSpace(docText.Text);
        }

        private void docText_TextChanged(object sender, TextChangedEventArgs e)
        {
            ValidateForm();
        }
    }
}
